package com.lukk.controller;

import java.security.interfaces.RSAPrivateKey;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpSession;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.lukk.constant.Const;
import com.lukk.pojo.InternalWorker;
import com.lukk.pojo.Province;
import com.lukk.pojo.Resource;
import com.lukk.service.IInternalWorkerService;
import com.lukk.service.IResourceService;
import com.lukk.util.JsonUtil;
import com.lukk.util.RSAUtils;
import com.lukk.util.RightsHelper;

/**
 * 
 * InternalWorkerController 下午6:39:26 Copyright zhaocj Inc. All Rights reserved.
 * alldios@outlook.com
 *
 */
@Controller
@RequestMapping("/internalWorker")
public class InternalWorkerController {
	private static Logger logger = LogManager.getLogger(InternalWorkerController.class.getName());
	@Autowired
	private IInternalWorkerService internalWorkerService;

	public IInternalWorkerService getInternalWorkerService() {
		return internalWorkerService;
	}

	public void setInternalWorkerService(IInternalWorkerService internalWorkerService) {
		this.internalWorkerService = internalWorkerService;
	}

	@javax.annotation.Resource
	IResourceService resourceService;

	// 解析视图
	@RequestMapping("/allocateProvince")
	public String allocateProvince(Model model) {
		model.addAttribute("oneMenu", "internalWorkerManage");
		model.addAttribute("twoMenu", "allocateProvince");
		return "/cms/internalWorkerManage/allocateProvince";
	}

	// 解析视图
	@RequestMapping("/allocateMerchant")
	public String workerInstallIndent(Model model) {
		model.addAttribute("oneMenu", "internalWorkerManage");
		model.addAttribute("twoMenu", "allocateMerchant");
		return "/cms/internalWorkerManage/allocateMerchant";
	}

	// 解析视图
	@RequestMapping("/employeeAnalyse")
	public String employeeAnalyse(Model model) {
		model.addAttribute("oneMenu", "internalWorkerManage");
		model.addAttribute("twoMenu", "employeeAnalyse");
		return "/cms/internalWorkerManage/employeeAnalyse";
	}

	/**
	 * 内部员工登录操作
	 * 
	 * @param workerCode
	 *            内部员工的标识
	 * @param password
	 *            内部员工的密码
	 * @param session
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/login")
	public @ResponseBody boolean login(String workerCode, String password, HttpSession session) throws Exception {
		logger.debug("===================开始进行登陆操作=====================");
		RSAPrivateKey privateKey = (RSAPrivateKey) session.getAttribute("privateKey");
		String descrypedPwd = RSAUtils.decryptByPrivateKey(password, privateKey); // 解密后的密码,password
		try {
			SecurityUtils.getSubject().login(new UsernamePasswordToken(workerCode, descrypedPwd));
			Integer[] rightsId = resourceService.queryMenuRightsByManager(workerCode);
			logger.debug("当前用户可以享用的资源有：{}", JsonUtil.toJson(rightsId));
			if (rightsId.length == 0) {
				session.setAttribute("menuList", null);
			} else {
				List<Resource> resources = resourceService.queryMenuResources();
				for (Resource resource : resources) {
					List<Resource> children = resource.getChildren();
					for (Resource resource2 : children) {
						resource2.setHasResource(
								RightsHelper.testRights(RightsHelper.sumRights(rightsId), resource2.getId()));
					}
					resource.setHasResource(
							RightsHelper.testRights(RightsHelper.sumRights(rightsId), resource.getId()));
				}
				logger.debug("当前用户可以享用的资源对象有：{}", JsonUtil.toJson(resources));
				session.setAttribute("menuList", resources);
			}
		} catch (AuthenticationException e) {
			logger.error("用户名或密码错误");
			return false;
		}
		return true;

	}

	/*
	 * @RequestMapping("/modify") public @ResponseBody boolean
	 * modify(InternalWorker internalWorker) { return
	 * internalWorkerService.modifyByPrimaryKey(internalWorker); }
	 */

	@RequestMapping("/logout")
	public @ResponseBody boolean logout(HttpSession session) {
		session.setAttribute(Const.SESSION_USER, null);
		SecurityUtils.getSubject().logout();
		return true;
	}

	// 分页查询
	@RequestMapping("/queryByPage")
	public @ResponseBody Map<String, Object> queryByPage(Integer offset, Integer limit, String sort, String order,
			InternalWorker internalWorker) throws Throwable {
		return internalWorkerService.selectByPage(offset, limit, sort, order, internalWorker);
	}

	/**
	 * 根据省份姓名进行模糊查询返回分配的内部员工
	 * 
	 * @param province
	 * @return
	 * @throws Throwable
	 */
	@RequestMapping("/queryInternalWorkerByProvince")
	public @ResponseBody InternalWorker queryInternalWorkerByProvince(Province province) {
		InternalWorker internalWorker = null;
		try {
			internalWorker = internalWorkerService.selectInternalWorkerByProvince(province);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return internalWorker;
	}
}
